//
//  IMLoginService.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/6/23.
//

#import "IMLoginService.h"
#import "../HTTP/YKHTTPService.h"
#import "../../Utils/Logger/IMLogUtils.h"

@implementation IMLoginService

static IMLoginService *_sharedService = nil;
static dispatch_once_t _onceToken;

+ (instancetype)sharedService {
    dispatch_once(&_onceToken, ^{
        _sharedService = [[IMLoginService alloc] init];
    });
    return _sharedService;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [IMLogUtils info:IMLogTagAd format:@"IMLoginService initialized"];
    }
    return self;
}

#pragma mark - 登录接口

- (IMNetworkTask *)loginWithAppId:(NSString *)appId
                         iosUuid:(NSString *)iosUuid
                     countryCode:(NSString *)countryCode
                         success:(IMLoginSuccessBlock)success
                         failure:(IMLoginFailureBlock)failure {
    
    // 参数验证
    if (!appId || appId.length == 0) {
        NSError *error = [NSError errorWithDomain:@"IMLoginService" 
                                             code:-1001 
                                         userInfo:@{NSLocalizedDescriptionKey: @"app_id不能为空"}];
        [IMLogUtils error:IMLogTagAd format:@"Login failed: app_id is required"];
        if (failure) {
            failure(error);
        }
        return nil;
    }
    
    if (!iosUuid || iosUuid.length == 0) {
        NSError *error = [NSError errorWithDomain:@"IMLoginService" 
                                             code:-1002 
                                         userInfo:@{NSLocalizedDescriptionKey: @"ios_uuid不能为空"}];
        [IMLogUtils error:IMLogTagAd format:@"Login failed: ios_uuid is required"];
        if (failure) {
            failure(error);
        }
        return nil;
    }
    
    // 创建请求模型
    IMLoginRequest *request = [IMLoginRequest requestWithAppId:appId 
                                                      iosUuid:iosUuid 
                                                  countryCode:countryCode];
    
    return [self loginWithRequest:request success:success failure:failure];
}

- (IMNetworkTask *)loginWithRequest:(IMLoginRequest *)request
                            success:(IMLoginSuccessBlock)success
                            failure:(IMLoginFailureBlock)failure {
    
    if (!request) {
        NSError *error = [NSError errorWithDomain:@"IMLoginService" 
                                             code:-1000 
                                         userInfo:@{NSLocalizedDescriptionKey: @"登录请求参数不能为空"}];
        [IMLogUtils error:IMLogTagAd format:@"Login failed: request is nil"];
        if (failure) {
            failure(error);
        }
        return nil;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"Starting login request for app_id: %@, ios_uuid: %@", 
     request.app_id, request.ios_uuid];
    
    // 准备请求参数
    NSDictionary *parameters = [request toDictionary];
    
    [IMLogUtils debug:IMLogTagAd format:@"Login request parameters: %@", parameters];
    
    // 发送POST请求到 /api/wsdk/login
    return [YKHTTPService POST:@"/api/wsdk/login"
                    parameters:parameters
                       success:^(IMNetworkResponse *response) {
                           [IMLogUtils info:IMLogTagAd format:@"Login request completed with status: %ld", (long)response.statusCode];
                           
                           // 解析响应数据
                           IMLoginResponse *loginResponse = nil;
                           
                           if (response.data && [response.data isKindOfClass:[NSDictionary class]]) {
                               loginResponse = [IMLoginResponse responseFromDictionary:(NSDictionary *)response.data];
                               [IMLogUtils debug:IMLogTagAd format:@"Parsed login response: %@", loginResponse];
                           } else {
                               [IMLogUtils warning:IMLogTagAd format:@"Invalid response data format: %@", response.data];
                               loginResponse = [[IMLoginResponse alloc] init];
                               loginResponse.code = response.statusCode;
                               loginResponse.message = @"响应数据格式错误";
                           }
                           
                           if (loginResponse.isSuccess) {
                               [IMLogUtils info:IMLogTagAd format:@"Login successful for user: %@", loginResponse.data.uuid];
                               if (success) {
                                   success(loginResponse);
                               }
                           } else {
                               [IMLogUtils warning:IMLogTagAd format:@"Login failed with code: %ld, message: %@", 
                                (long)loginResponse.code, loginResponse.message];
                               NSError *error = [NSError errorWithDomain:@"IMLoginService" 
                                                                    code:loginResponse.code 
                                                                userInfo:@{NSLocalizedDescriptionKey: loginResponse.message ?: @"登录失败"}];
                               if (failure) {
                                   failure(error);
                               }
                           }
                       }
                       failure:^(IMNetworkResponse *response) {
                           [IMLogUtils error:IMLogTagAd format:@"Login network request failed: %@", response.error.localizedDescription];
                           if (failure) {
                               failure(response.error);
                           }
                       }];
}

#pragma mark - Description

- (NSString *)description {
    return [NSString stringWithFormat:@"<%@: %p>", NSStringFromClass([self class]), self];
}

@end